const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const chalk = require("chalk");
const feishuService = require("./feishu");
const generators = require("../generators");

class I18nServer {
  constructor() {
    this.app = new Koa();
    this.router = new Router();
    this.setupMiddleware();
    this.setupRoutes();
  }

  setupMiddleware() {
    // 错误处理
    this.app.use(async (ctx, next) => {
      try {
        await next();
      } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = {
          success: false,
          error: err.message,
          code: ctx.status,
        };
        console.error(chalk.red("API Error:"), err.message);
      }
    });

    // 请求日志
    this.app.use(async (ctx, next) => {
      const start = Date.now();
      await next();
      const ms = Date.now() - start;
      console.log(chalk.gray(`${ctx.method} ${ctx.url} - ${ms}ms`));
    });

    // 解析请求体
    this.app.use(bodyParser());

    // CORS
    this.app.use(async (ctx, next) => {
      ctx.set("Access-Control-Allow-Origin", "*");
      ctx.set(
        "Access-Control-Allow-Methods",
        "GET, POST, PUT, DELETE, OPTIONS"
      );
      ctx.set("Access-Control-Allow-Headers", "Content-Type, Authorization");

      if (ctx.method === "OPTIONS") {
        ctx.status = 200;
        return;
      }

      await next();
    });
  }

  setupRoutes() {
    // 健康检查
    this.router.get("/", (ctx) => {
      ctx.body = {
        success: true,
        message: "🌍 i18n-CLI API 服务运行中",
        version: "1.0.0",
        endpoints: [
          "POST /auth - 飞书认证",
          "GET /sheets/:spreadsheetToken - 获取工作表列表",
          "GET /sheets/:spreadsheetToken/:sheetId/data - 获取表格数据",
          "POST /generate - 生成多语言文件",
        ],
      };
    });

    // 飞书认证
    this.router.post("/auth", async (ctx) => {
      const { appKey, appSecret } = ctx.request.body;

      if (!appKey || !appSecret) {
        ctx.throw(400, "appKey 和 appSecret 是必需的");
      }

      const accessToken = await feishuService.authenticate(appKey, appSecret);

      ctx.body = {
        success: true,
        message: "认证成功",
        data: {
          accessToken,
          expiresIn: 7200,
        },
      };
    });

    // 获取工作表列表
    this.router.get("/sheets/:spreadsheetToken", async (ctx) => {
      const { spreadsheetToken } = ctx.params;

      const sheets = await feishuService.getSheets(spreadsheetToken);

      ctx.body = {
        success: true,
        data: {
          sheets: sheets.map((sheet) => ({
            id: sheet.sheet_id,
            title: sheet.title,
            index: sheet.index,
            hidden: sheet.hidden,
          })),
        },
      };
    });

    // 获取表格数据
    this.router.get("/sheets/:spreadsheetToken/:sheetId/data", async (ctx) => {
      const { spreadsheetToken, sheetId } = ctx.params;
      const { range } = ctx.query;

      const data = await feishuService.getSheetData(
        spreadsheetToken,
        sheetId,
        range
      );

      // 转换为i18n格式
      const i18nData = this.transformTableDataToI18n(data);

      ctx.body = {
        success: true,
        data: {
          raw: data,
          i18n: i18nData,
          languages: i18nData.languages || [],
          keys: i18nData.keys || [],
        },
      };
    });

    // 生成多语言文件
    this.router.post("/generate", async (ctx) => {
      const {
        spreadsheetToken,
        sheetId,
        platform,
        languages,
        formats,
        appKey,
        appSecret,
      } = ctx.request.body;

      // 验证必需参数
      if (
        !spreadsheetToken ||
        !sheetId ||
        !platform ||
        !languages ||
        !formats
      ) {
        ctx.throw(400, "缺少必需参数");
      }

      if (!Array.isArray(languages) || !Array.isArray(formats)) {
        ctx.throw(400, "languages 和 formats 必须是数组");
      }

      // 如果提供了认证信息，重新认证
      if (appKey && appSecret) {
        await feishuService.authenticate(appKey, appSecret);
      }

      // 获取表格数据
      const tableData = await feishuService.getSheetData(
        spreadsheetToken,
        sheetId
      );
      const i18nData = this.transformTableDataToI18n(tableData);

      // 生成文件内容
      const generatedFiles = {};

      for (const language of languages) {
        if (!i18nData.data[language]) {
          continue;
        }

        for (const format of formats) {
          const key = `${language}.${format}`;
          const content = await generators.generateContent(
            format,
            i18nData.data[language],
            platform
          );
          generatedFiles[key] = content;
        }
      }

      ctx.body = {
        success: true,
        data: {
          files: generatedFiles,
          meta: {
            platform,
            languages,
            formats,
            totalFiles: Object.keys(generatedFiles).length,
            availableLanguages: i18nData.languages,
          },
        },
      };
    });

    // 获取表格信息
    this.router.get("/info/:spreadsheetToken", async (ctx) => {
      const { spreadsheetToken } = ctx.params;

      const info = await feishuService.getSheetInfo(spreadsheetToken);

      ctx.body = {
        success: true,
        data: info,
      };
    });

    this.app.use(this.router.routes());
    this.app.use(this.router.allowedMethods());
  }

  transformTableDataToI18n(tableData) {
    const result = {
      languages: [],
      keys: [],
      data: {},
    };

    if (!tableData || tableData.length === 0) {
      return result;
    }

    const headers = tableData[0]; // 第一行是标题
    const dataRows = tableData.slice(1); // 从第二行开始是数据

    // 第一列是key，其他列是语言
    result.languages = headers.slice(1).filter((lang) => lang && lang.trim());

    // 初始化各语言的数据对象
    result.languages.forEach((lang) => {
      result.data[lang] = {};
    });

    // 处理每一行数据
    dataRows.forEach((row) => {
      const key = row[0]; // 第一列是key
      if (!key || !key.trim()) return; // 跳过空key

      result.keys.push(key.trim());

      // 处理每种语言的值
      headers.slice(1).forEach((lang, index) => {
        if (lang && lang.trim() && result.data[lang]) {
          const value = row[index + 1] || ""; // +1 因为第一列是key
          result.data[lang][key.trim()] = value.trim();
        }
      });
    });

    return result;
  }

  async start(port = 3000) {
    return new Promise((resolve) => {
      const server = this.app.listen(port, () => {
        console.log(chalk.green("🚀 i18n-CLI API 服务启动成功!"));
        console.log(chalk.cyan(`📍 服务地址: http://localhost:${port}`));
        console.log(chalk.gray("按 Ctrl+C 停止服务\n"));
        resolve(server);
      });
    });
  }

  async stop(server) {
    return new Promise((resolve, reject) => {
      if (server) {
        server.close((err) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      } else {
        resolve();
      }
    });
  }
}

module.exports = {
  start: async (port) => {
    const server = new I18nServer();
    await server.start(port);
  },
  startServer: async (port) => {
    const server = new I18nServer();
    return await server.start(port);
  },
  stopServer: async (serverInstance) => {
    const server = new I18nServer();
    return await server.stop(serverInstance);
  },
};
